package com.hxm.downloadtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    private Button button,btnShow;
    private GifImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.btn_download);
        imageView = (GifImageView) findViewById(R.id.gif_image);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downloadImage();
            }
        });
        btnShow = (Button) findViewById(R.id.btn_show);
        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File file=new File(getExternalFilesDir(null),"hahah.gif");
                    GifDrawable gifDrawable=new GifDrawable(file);
                    imageView.setImageDrawable(gifDrawable);
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.i("IOException"," "+e.toString()+getExternalFilesDir(null).getPath());
                }
            }
        });
    }

    private void downloadImage() {
        Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl("http://wimg.spriteapp.cn/")
                .build();
        ApiService service = retrofit.create(ApiService.class);
        service.downloadImage("ugc/2017/01/04/586d166add541.gif")
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Action1<ResponseBody>() {
                    @Override
                    public void call(ResponseBody responseBody) {
                        boolean complete = writeToDisk(responseBody);
                        Log.i("is download success?"," "+complete);
                        if (complete){
                            Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.i("error",throwable.toString());
                    }
                });
//        service.downloadService("http://wimg.spriteapp.cn/ugc/2017/01/04/586d166add541.gif")
//                .enqueue(new Callback<ResponseBody>() {
//                    @Override
//                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//
//                    }
//
//                    @Override
//                    public void onFailure(Call<ResponseBody> call, Throwable t) {
//
//                    }
//                });
    }

    private boolean writeToDisk(ResponseBody body) {
        File gifFile = new File(getExternalFilesDir(null) + File.separator + "hahah.gif");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        //缓冲大小
        byte[] readByte = new byte[4096];

        long fileSize = body.contentLength();
        long fileDownloadSize = 0;

        inputStream = body.byteStream();
        try {
            outputStream = new FileOutputStream(gifFile);
            while (true) {
                int read = inputStream.read(readByte);
                if (read == -1) {
                    break;
                }

                outputStream.write(readByte, 0, read);
                fileDownloadSize += read;
                Log.i("download: ","FileDownload "+fileDownloadSize +"of"+ fileSize);
            }
            outputStream.flush();
            return true;
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
